<?php

class ThumbnailGenerator
{
    const DEFAULT_QUALITY = 85;
    const THUMBNAIL_WIDTH = 300;
    const THUMBNAIL_HEIGHT = 300;

    private $imgResource;
    private $imgWidth;
    private $imgHeight;

    /**
     * @throws ThumbnailGeneratorException
     * @param string $imgData binary data of image for thumbnail generation
     */
    public function __construct( $imgData )
    {
        $imgResource = @imagecreatefromstring($imgData);
        if ( !$imgResource )
        {
            throw new ThumbnailGeneratorException(ThumbnailGeneratorException::RESOURCE_CREATION_ERROR);
        }
        $this->imgWidth = imagesx($imgResource);
        $this->imgHeight = imagesy($imgResource);
        $this->imgResource = $imgResource;
    }

    public function IsSourceValid()
    {
        return ( ( $this->imgWidth >= self::THUMBNAIL_WIDTH ) && ( $this->imgHeight >= self::THUMBNAIL_HEIGHT ) );
    }

    public function Generate()
    {
        $imgTo = imagecreatetruecolor(self::THUMBNAIL_WIDTH, self::THUMBNAIL_HEIGHT);
        imagecopyresampled($imgTo, $this->imgResource, 0, 0, 0, 0, self::THUMBNAIL_WIDTH, self::THUMBNAIL_HEIGHT, self::THUMBNAIL_WIDTH, self::THUMBNAIL_HEIGHT);
        ob_start();
        imagepng($imgTo);
        $resultingImage = ob_get_clean();
        return $resultingImage;
    }

    public function getWidth()
    {
        return $this->imgWidth;
    }

    public function getHeight()
    {
        return $this->imgHeight;
    }
}

?>